package com.shop.service.impl;

import com.shop.mapper.IMenuMapper;
import com.shop.pojo.CommonResult;
import com.shop.pojo.MenuTemplate;
import com.shop.service.IMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MenuServiceImpl implements IMenuService {
    @Resource
    private IMenuMapper menuMapper;

    @Override
    public CommonResult<List<MenuTemplate>> getMenus() {
        List<MenuTemplate> parent = menuMapper.getMenusByPID();
        for (MenuTemplate menu : parent) {
            parseIntoTree(menu);
        }
        return new CommonResult<>(200, "success", parent);
    }

    private void parseIntoTree(MenuTemplate parent) {
        int id = parent.getId();
        List<MenuTemplate> children = menuMapper.getMenusByPID(id);
        if (children.size() != 0) {
            for (MenuTemplate child : children) {
                parseIntoTree(child);
            }
        }
        parent.setChildren(children);
    }
}
